
import { _decorator, Component, Node, Vec3, Prefab, SkeletalAnimation, Mat4, v3, Font } from 'cc';
import yyComponent from '../../Script/Common/yyComponent';
import { GlobalEnum } from '../../Script/GameSpecial/GlobalEnum';
import { EventType } from '../../Script/GameSpecial/GameEventType';
import GameConfig from '../../Script/GameSpecial/GameConfig';
import { BaseTransform } from './BaseTransform';
import GlobalPool, { customPoolScript } from '../../Script/Common/GlobalPool';
import Streak from './Streak';
import Loader from '../../Script/Common/Loader';
import PlayerData from '../../Script/Common/PlayerData';
import { ShopDataCfg } from '../../Script/GameSpecial/shopDataCfg';
import GlobalData from '../../Script/Common/GlobalData';

const car1_0 = { type: 1, id: 0, getType: 0, price: 200, width: 0.45, height: 1.3, len: 0.504, minSpeed: 10, maxSpeed: 15, totalPartCount: 12, rolePos: { x: 0, y: 0.2, z: 0 }, streakPos: [], streakWidth: 0.063 };

const { ccclass, property } = _decorator;
@ccclass('Role')
export class Role extends BaseTransform {

    /************************************************************通用流程************************************************************/
    protected initSub() {
        this.initBody();
        this.initCar();
        this.initCollPtr();
        this.initCollScope();
        this.initDirtyFlags();
        this.initHuoYan();
        this.initRadianZ();
        this.initSpeed();
        this.initStreak();
    }
    protected resetSub() {
        this.resetBody();
        this.resetCar();
        this.resetCollPtr();
        this.resetCollScope();
        this.resetDirtyFlags();
        this.resetHuoYan();
        this.resetRadianZ();
        this.resetSpeed();
        this.resetStreak();
    }
    protected registAllCustomUpdate() {
        this.registCustomUpdate(GlobalEnum.RoleState.stand, this.stepStand);
        this.registCustomUpdate(GlobalEnum.RoleState.move, this.stepMoving);
        this.registCustomUpdate(GlobalEnum.RoleState.endRoad, this.stepEndRoad);
        this.registCustomUpdate(GlobalEnum.RoleState.moveOnBadTerrain, this.stepMoveOnBadTerrain);
        this.registCustomUpdate(GlobalEnum.RoleState.moveToScoreLine, this.stepMoveToScoreLine);
        this.registCustomUpdate(GlobalEnum.RoleState.moveOnScoreRoad, this.stepMoveOnScoreRoad);

    }
    protected onEvents() {
        this.on(EventType.LevelEvent.removeBarrierGroupIndex, this.onRemoveBarrierGroupIndex, this);
    }

    protected setData(data: { z?: number, radian?: number }) {
        if (undefined !== data.z) {
            this.node.setPosition(0, 0, data.z);
            this.node.getPosition(this.cachePos);
        }
        if (undefined !== data.radian) {
            this.setRadianZ(data.radian);
            this.setTargetRadianZ(data.radian);
        }
    }

    /************************************************************对外功能************************************************************/
    public enterLevel(data?: { z?: number, radian: number }) {
        if (!!data) {
            if (undefined !== data.z) {
                this.node.setPosition(0, 0, data.z);
                this.node.getPosition(this.cachePos);
            }
            if (undefined !== data.radian) {
                this.setRadianZ(data.radian);
                this.setTargetRadianZ(data.radian);
            }
        }
        this.enterCustomUpdateState(GlobalEnum.RoleState.stand);
        if (this.isPlayer && GlobalData.get(GlobalEnum.myGlobalDataType.tryMaxCar)) {
            this.setCar(3, 3);
        } else {
            this.setCar(1, 0);
        }
        this.once(EventType.LevelEvent.startJoy, this.startLevel, this);
    }
    public setPartFull() {
        let count = this.car.getTotalPartCount();
        this.car.addPartCount(count);
        this.curPartCount = count;
        this.updateSpeed();
        this.showHuoYan();
        if (this.isPlayer) {
            this.emit(EventType.LevelEvent.playerPartFull);
        }
    }

    public onColl(data: { type: GlobalEnum.CollerType, item: yyComponent }) {
        switch (data.type) {
            case GlobalEnum.CollerType.barrierGroup: {
                this.onCollBarrier(data.item);
                break;
            }
            case GlobalEnum.CollerType.carPart: {
                this.onGetPart(data.item);
                break;
            }
            case GlobalEnum.CollerType.changeCarQuad: {
                this.onChangeCar(data.item);
                break;
            }
            case GlobalEnum.CollerType.gold: {
                this.onCollGold(data.item);
                break;
            }
            case GlobalEnum.CollerType.terrain: {
                this.onEnterTerrain(data.item);
                break;
            }
        }
    }
    protected onCollBarrier(item) {
        this.hideHuoYan();
        //震屏、音效
        if (this.isPlayer) {
            this.emit(EventType.Common.AudioEvent.playEffect, GlobalEnum.AudioClip.collBarrier, { isLoop: false, volume: 1 });
            this.emit(EventType.LevelEvent.shakeScreen, { duration: 0.2, radius: 0.3 });
        }
        //掉落零件
        if (this.car.getPartCount() == 0) {
            return;
        }
        let isFull = this.car.isPartFull();
        let count = Math.round(this.car.getPartCount() * 0.5);
        if (count > 40) {
            count = 40;
        } else if (count > 0 && count < 15) {
            count = 15;
        }
        count = this.car.dropPartCount(count);
        this.curPartCount = this.car.getPartCount();
        this.updateSpeed();
        if (this.isPlayer) {
            this.emit(EventType.Common.SDKEvent.vibrateShort);
            this.emit(EventType.LevelEvent.playerDropCarPart, { part: item, partCount: this.curPartCount, subCount: count });
            if (isFull) {
                this.emit(EventType.LevelEvent.playerPartExitFull);
            }
        }
    }
    //获得零件
    protected onGetPart(item) {
        if (this.isPlayer) {
            this.emit(EventType.Common.AudioEvent.playEffect, GlobalEnum.AudioClip.getCarPart, { volume: 1 });
        }
        if (this.isCarPartFull()) {
            this.enterPartAddSpeed();
            return;
        }
        let count = 0;
        // if (this.carType == 1 && this.carId == 0) {
        //     count = 2;
        // } else {
        // }
        count = Math.ceil(this.car.getTotalPartCount() / this.car.getPartGroupCount());
        if (!!item && item.node.name == "CarPart2") {
            count *= 2;
        }
        let isFull = this.car.isPartFull();
        count = this.car.addPartCount(count);
        this.curPartCount = this.car.getPartCount();
        this.updateSpeed();
        if (this.car.isPartFull()) {
            this.showHuoYan();
        }
        if (this.isPlayer) {
            this.emit(EventType.LevelEvent.playerGetCarPart, { part: item, partCount: this.curPartCount, addCount: count });
            if (!isFull && this.car.isPartFull()) {
                this.emit(EventType.LevelEvent.playerPartFull);
            }
        }
    }

    protected onChangeCar(quad) {
        if (this.isPlayer) {
            if (this.collPtr[GlobalEnum.CollerType.changeCarQuad].min == 0 && GlobalData.get(GlobalEnum.myGlobalDataType.tryMaxCar)) {
                this.collPtr[GlobalEnum.CollerType.changeCarQuad].min += 1;
                GlobalData.set(GlobalEnum.myGlobalDataType.tryMaxCar, false);
                return;
            }
        }
        let car = quad.cars[0];
        if (this.radianZ > 0) {
            car = quad.cars[1];
        }
        //todo:变换车辆模型
        let id = 0;
        if (this.isPlayer) {
            //玩家皮肤
            // id = PlayerData.getData("gameData.useSkin")[car];
            id = PlayerData.getCarSkinId(car);
        } else {
            //随机皮肤
            id = Math.floor(Math.random() * 2.999) + 1;
        }
        this.changeCar(car, id);

        if (this.isPlayer) {
            this.emit(EventType.Common.AudioEvent.playEffect, GlobalEnum.AudioClip.changeCar);
            this.emit(EventType.LevelEvent.playerChangeCar, { car: car, totalPartCount: this.totalPartCount, curPartCount: this.curPartCount });
            this.emit(EventType.LevelEvent.playerCollChangeCarQuad, { index: this.collPtr[GlobalEnum.CollerType.changeCarQuad].min, car: car });
        } else {
            this.emit(EventType.LevelEvent.enemyChangeCar, { car: car, role: this });
        }
        this.collPtr[GlobalEnum.CollerType.changeCarQuad].min += 1;
    }
    protected onCollGold(gold: yyComponent) {
        if (this.isPlayer) {
            this.emit(EventType.Common.AudioEvent.playEffect, GlobalEnum.AudioClip.gold);
            this.emit(EventType.LevelEvent.playerCollGold, gold);
        }
    }
    protected onEnterTerrain(item) {
        if (item.type == this.carType) {
            this.enterTerrain(item);
            this.enterCustomUpdateState(GlobalEnum.RoleState.moveOnBadTerrain);
            if (this.isPlayer) {
                this.emit(EventType.LevelEvent.playerEnterTerrain);
            }
        }
    }

    public isCarPartFull() {
        return this.curPartCount >= this.totalPartCount;
    }

    public moveToScoreLine() {
        this.targetRadianZ = 0;
        this.node.active = true;
        this.enterCustomUpdateState(GlobalEnum.RoleState.moveToScoreLine);
    }

    public enterScoreRoad() {
        // console.error("玩家加零件");
        // this.car.addPartCount(100);
        this.node.active = true;
        this.hideHuoYan();
        this.updateSpeed();
        this.enterCustomUpdateState(GlobalEnum.RoleState.moveOnScoreRoad);
    }

    public getCurPartCount() {
        return this.curPartCount;
    }

    public startLevel() {
        this.enterCustomUpdateState(GlobalEnum.RoleState.move);
        this.playRun();
    }

    /************************************************************状态数据************************************************************/
    protected _isPlayer: boolean = false;
    public get isPlayer() { return this._isPlayer; }

    //#region 移动属性
    /**移动速度值 */
    protected get speedValue() {
        if (!!this.car) {
            return this.car.getSpeed() * this.speedScale + this.partAddSpeed;
        } else {
            return GameConfig.GameRule.moveSpeed * this.speedScale + this.partAddSpeed;
        }
    }
    protected speedScale: number = 1;
    //捡取额外的零件增加的速度，0.5秒内衰减到0，最大值5
    protected partAddSpeed: number = 0;
    protected partAddSpeedMax: number = 10;
    protected partAddSpeedDuration: number = 2;
    /**实时速度 */
    protected speed: Vec3;
    protected cachePos: Vec3;
    protected initSpeed() {
        this.speedScale = 1;
        this.speed = new Vec3();
        this.speed.z = -this.speedValue;
        this.cachePos = new Vec3();
        this.partAddSpeed = 0;
    }
    protected resetSpeed() {
        this.speedScale = 1;
        this.speed.z = -this.speedValue;
        this.partAddSpeed = 0;
    }
    protected updateSpeed() {
        this.speed.z = -this.speedValue;
    }
    protected updatePartAddSpeed(dt: number) {
        if (this.partAddSpeed == 0) return;
        this.partAddSpeed -= this.partAddSpeedMax * dt / this.partAddSpeedDuration;
        if (this.partAddSpeed <= 0) {
            this.partAddSpeed = 0;
        }
        this.updateSpeed();
    }
    protected enterPartAddSpeed() {
        console.log("进入加速状态");
        if (this.partAddSpeed == 0 && this.isPlayer) {
            //todo:播放声音

        }
        this.partAddSpeed = this.partAddSpeedMax;
    }
    //#endregion

    //#region 碰撞范围
    /**车辆宽度 */
    public width: number;
    /**车辆高度 */
    public height: number;
    /**车辆长度 */
    public len: number;
    /**车辆底部的弧度范围 */
    protected radianScope: number;
    protected zScope: number;
    protected initCollScope() {
        this.width = 1;
        this.height = 1;
        this.len = 1;
        this.radianScope = this.width * 0.5 / GameConfig.GameRule.roadHalfWidth;
        this.minRadian = -this.radianScope;
        this.maxRadian = this.radianScope;
        this.zScope = this.len * 0.5;
        this.minZ = -this.zScope;
        this.maxZ = this.zScope;
    }
    protected resetCollScope() {

    }
    protected updateCollScope() {
        this.minRadian = this.radianZ - this.radianScope;
        this.maxRadian = this.radianZ + this.radianScope;
        this.minZ = this.cachePos.z - this.zScope;
        this.maxZ = this.cachePos.z + this.zScope;
    }
    protected updateCarSize() {
        let size = this.car.getSize();
        this.width = size.width;
        this.height = size.height;
        this.len = size.len;
        this.radianScope = this.width * 0.5 / GameConfig.GameRule.roadHalfWidth;
        this.zScope = this.len * 0.5;
        this.updateCollScope();
    }
    //#endregion

    //#region 旋转角度
    /**模型与圆心连线与Y轴负向的夹角弧度 */
    public radianZ: number;
    protected startRadianZ: number;
    protected targetRadianZ: number;
    protected radianSpeed: number;
    protected initRadianZ() {
        this.radianZ = 0;
        this.startRadianZ = 0;
        this.targetRadianZ = 0;
        this.radianSpeed = Math.PI * 0.6;
        if (!this.isPlayer) {
            this.radianSpeed *= 0.3;
        }
        this.node.setRotation(0, 0, 0, 1);
    }
    protected resetRadianZ() {
        this.radianZ = 0;
        this.startRadianZ = 0;
        this.targetRadianZ = 0;
        this.node.setRotation(0, 0, 0, 1);
    }
    protected setRadianZ(r) {
        this.radianZ = r;
        this.node.setRotation(0, 0, Math.sin(r * 0.5), Math.cos(r * 0.5));
    }
    protected setTargetRadianZ(r) {
        if (r < GameConfig.GameRule.roadMinRadian + 0.1) {
            this.targetRadianZ = GameConfig.GameRule.roadMinRadian + 0.1;
        } else if (r > GameConfig.GameRule.roadMaxRadian - 0.1) {
            this.targetRadianZ = GameConfig.GameRule.roadMaxRadian - 0.1;
        } else {
            this.targetRadianZ = r;
        }
    }
    protected rotateToTargetRadianZ(dt: number) {
        if (this.radianZ == this.targetRadianZ) {
            return;
        }
        let r = this.targetRadianZ;
        let step = this.radianSpeed * dt;
        let rot: boolean = false;
        if (step < Math.abs(this.targetRadianZ - this.radianZ)) {
            if (this.targetRadianZ > this.radianZ) {
                r = this.radianZ + step;
            } else {
                r = this.radianZ - step;
            }
            rot = true;
        }
        this.setRadianZ(r);
        if (this.carId == 0) return;
        if (rot) {
            r = (this.targetRadianZ - this.radianZ) * 57.3;
            let y = -r;
            let z = 0;
            if (this.carType == 1) {
                y *= 2;
                z = -r;
            }
            this.carLayer.setRotationFromEuler(0, y, z);
        } else {
            this.carLayer.setRotationFromEuler(0, 0, 0);
        }

    }
    //#endregion

    //#region 可碰撞物索引范围
    public collPtr: { [type: number]: { min: number, max: number } };
    protected initCollPtr() {
        this.collPtr = {};
        this.collPtr[GlobalEnum.CollerType.barrierGroup] = { min: 0, max: 0 };
        this.collPtr[GlobalEnum.CollerType.changeCarQuad] = { min: 0, max: 0 };
        this.collPtr[GlobalEnum.CollerType.gold] = { min: 0, max: 0 };
        this.collPtr[GlobalEnum.CollerType.terrain] = { min: 0, max: 0 };
        this.collPtr[GlobalEnum.CollerType.carPart] = { min: 0, max: 0 };
    }
    protected resetCollPtr() {
        for (let key in this.collPtr) {
            this.collPtr[key].min = 0;
            this.collPtr[key].max = 0;
        }
    }

    //#endregion

    //#region 所处不利地形
    protected terrain: BaseTransform;
    protected initTerrain() { }
    protected resetTerrain() {
        this.terrain = null;
    }
    protected enterTerrain(terrain) {
        this.terrain = terrain;
        this.speedScale = 0.5;
        this.updateSpeed();
        this.hideHuoYan();
    }
    protected exitTerrain() {
        this.terrain = null;
        this.speedScale = 1;
        this.updateSpeed();
        if (this.car.isPartFull()) {
            this.showHuoYan();
        }
    }
    //#endregion

    /************************************************************管理对象************************************************************/
    protected getCarScale() {
        switch (this.carType) {
            case 1: {
                // return this.carId > 0 ? 2 : 1;
                return 2;
            }
            case 2: return 1.3;
            case 3: {
                return this.carId == 3 ? 1 : 1.4;
            }
        }
        return 1;
    }

    //#region 人物
    @property(Node)
    protected body: Node = null;
    @property(SkeletalAnimation)
    protected anim: SkeletalAnimation = null;
    //人物的背包
    @property(Node)
    protected bag: Node = null;
    protected initBody() {
        this.bag.active = true;
        this.body.setPosition(0, 0, 0);
        this.playStand();
        setTimeout(() => {
            this.anim.getState(GlobalEnum.RoleAnimName.car1_0).speed = 2;
        }, 0);
    }
    protected resetBody() {
        this.bag.active = true;
        this.body.setPosition(0, 0, 0);
        this.playStand();
    }
    protected updateRoleState() {
        let s = this.getCarScale();
        this.carLayer.setScale(s, s, s);
        this.bag.active = this.carId == 0;
        let data = this.car.getCarData();
        this.body.setPosition(data.rolePos);
        if (this.carId === 0 && this.customUpdateState === GlobalEnum.RoleState.stand) {
            this.playStand();
        } else {
            this.playRun();
        }
    }
    protected playStand() {
        this.anim.play(GlobalEnum.RoleAnimName.stand);
    }
    protected playRun() {
        this.anim.play(GlobalEnum.RoleAnimName["car" + this.carType + "_" + this.carId]);
    }
    //#endregion

    //#region 车辆
    @property(Node)
    protected carLayer: Node = null;
    protected car = null;
    protected carType: number = 1;
    protected carId: number = 0;
    protected curPartCount: number = 0;
    protected totalPartCount: number = 12;
    protected preCarPartCount: number = 0;
    protected initCar() { }
    protected resetCar() {
        this.curPartCount = 0;
        this.carLayer.setRotation(0, 0, 0, 1);
        this.setCar(1, 0);
    }
    protected getCarData() {
        if (this.carType == 1 && this.carId == 0) {
            return car1_0;
        } else {
            return ShopDataCfg[this.carType][this.carId - 1];
        }
    }
    protected setCar(type: number, id: number) {
        this.carType = type;
        this.carId = id;
        let data = this.getCarData();
        this.totalPartCount = data.totalPartCount;
        if (this.curPartCount >= this.totalPartCount) {
            this.curPartCount = this.totalPartCount;
            if (this.isPlayer) {
                this.emit(EventType.LevelEvent.playerPartFull);
            }
        } else {
            if (this.isPlayer) {
                this.emit(EventType.LevelEvent.playerPartExitFull);
            }
        }

        let str = "car" + type + "_" + id;
        let node = GlobalPool.get(str);
        if (!node) {
            Loader.loadBundle("Car", () => {
                Loader.loadBundleRes("Car", "Prefab/Level/" + str, (res) => {
                    if (!res) {
                        return;
                    }
                    GlobalPool.createPool(str, res, "Car");
                    node = GlobalPool.get(str);
                    this.addCarNode(node);
                });
            }, false, false);
        } else {
            this.addCarNode(node);
        }
    }
    protected addCarNode(node) {
        this.removeCar();
        this.carLayer.addChild(node);
        this.car = node[customPoolScript];
        // this.car.setPartCount(this.curPartCount);
        if (this.curPartCount > 0) {
            this.car.addPartCount(this.curPartCount);
        }
        this.updateCarSize();
        this.updateCarStreaks();
        this.updateRoleState();
        this.updateSpeed();
        this.updateCarHuoYan();
    }
    protected removeCar() {
        if (!!this.car) {
            GlobalPool.put(this.car.node);
            this.car = null;
        }
    }
    //变换车辆
    protected changeCar(type: number, id: number) {
        if (!!this.car) {
            this.preCarPartCount = this.car.getPartCount();
        } else {
            this.preCarPartCount = 0;
        }
        this.setCar(type, id);
    }
    //#endregion

    //#region 轮胎轨迹拖尾
    protected streaks: Streak[] = null;
    protected streakPos: { x: number, y: number, z: number }[] = [];
    protected cacheStreakTopP: Vec3 = null;
    protected cacheStreakBottomP: Vec3 = null;
    protected streakWidth: number = 0.2;
    protected carMat4: Mat4 = null;
    protected initStreak() {
        this.streakPos = [];
        this.streaks = [];
        this.cacheStreakTopP = new Vec3();
        this.cacheStreakBottomP = new Vec3();
        this.carMat4 = new Mat4();
    }
    protected resetStreak() {
        if (this.streaks.length > 0) {
            this.emit(EventType.LevelEvent.removeCarStreak, this.streaks);
            this.streaks = [];
            this.streakPos = [];
        }
    }
    protected updateCarStreaks() {
        this.resetStreak();
        let s = this.getCarScale();
        this.streakPos = [];
        let dd = this.car.getStreakPos();
        for (let i = dd.length - 1; i >= 0; --i) {
            this.streakPos.push(v3(dd[i].x * s, dd[i].y * s, dd[i].z * s));
        }
        this.streakWidth = this.car.getCarData().streakWidth * s;
        let w = this.streakWidth * 0.5;
        let sin = Math.sin(this.radianZ);
        let cos = Math.cos(this.radianZ);
        let offsetY = this.car.node.parent.position.y;
        for (let i = 0; i < this.streakPos.length; ++i) {
            let node = GlobalPool.get("Streak");
            let js: Streak = node[customPoolScript];
            let p = this.streakPos[i];
            let x = p.x + w;
            let y = p.y + offsetY;
            this.cacheStreakTopP.x = x * cos - y * sin;
            this.cacheStreakTopP.y = x * sin + y * cos;
            this.cacheStreakTopP.z = this.z + p.z;
            x = p.x - w;
            this.cacheStreakBottomP.x = x * cos - y * sin;
            this.cacheStreakBottomP.y = x * sin + y * cos;
            this.cacheStreakBottomP.z = this.z + p.z;
            js.play({
                topPos: this.cacheStreakTopP,
                bottomPos: this.cacheStreakBottomP,
            });
            this.streaks.push(js);
        }
        this.emit(EventType.LevelEvent.addCarStreak, this.streaks);
    }
    protected updateStreaks(dt: number) {
        let w = this.streakWidth * 0.5;
        // let sin = Math.sin(this.radianZ);
        // let cos = Math.cos(this.radianZ);
        // let offsetY = this.car.node.parent.position.y;
        this.carLayer.getWorldRT(this.carMat4);
        for (let i = this.streakPos.length - 1; i >= 0; --i) {
            let js: Streak = this.streaks[i];
            let p = this.streakPos[i];
            this.cacheStreakTopP.set(p);
            this.cacheStreakTopP.x += w;
            Vec3.transformMat4(this.cacheStreakTopP, this.cacheStreakTopP, this.carMat4);
            this.cacheStreakBottomP.set(p);
            this.cacheStreakBottomP.x -= w;
            Vec3.transformMat4(this.cacheStreakBottomP, this.cacheStreakBottomP, this.carMat4);
            js.moveTo(this.cacheStreakTopP, this.cacheStreakBottomP);
        }
    }
    //#endregion

    //#region 加速效果：尾部火焰
    protected huoYanNodes: Node[] = [];
    protected initHuoYan() {

    }
    protected resetHuoYan() {
        if (!!this.huoYanNodes[0]) {
            GlobalPool.put(this.huoYanNodes[0]);
        }
        if (!!this.huoYanNodes[1]) {
            GlobalPool.put(this.huoYanNodes[1]);
        }
        this.huoYanNodes = [];
    }
    protected showHuoYan() {
        if (!!this.huoYanNodes[0]) this.huoYanNodes[0].active = true;
        if (!!this.huoYanNodes[1]) this.huoYanNodes[1].active = true;
    }
    protected hideHuoYan() {
        if (!!this.huoYanNodes[0]) this.huoYanNodes[0].active = false;
        if (!!this.huoYanNodes[1]) this.huoYanNodes[1].active = false;
    }
    protected updateCarHuoYan() {
        let cs = this.getCarScale();
        let s = v3(1.5, 3, 1.5).multiplyScalar(1 / cs);
        let data = this.car.getHuoYanPos();

        if (!!data[0]) {
            if (!this.huoYanNodes[0]) {
                let node = GlobalPool.get("HuoYan");
                this.carLayer.addChild(node);
                node.setPosition(data[0]);
                this.huoYanNodes[0] = node;
            }
            this.huoYanNodes[0].setPosition(data[0]);
            this.huoYanNodes[0].setScale(s);
        } else {
            if (!!this.huoYanNodes[0]) {
                GlobalPool.put(this.huoYanNodes[0]);
                this.huoYanNodes[0] = null;
            }
        }
        if (!!data[1]) {
            if (!this.huoYanNodes[1]) {
                let node = GlobalPool.get("HuoYan");
                this.carLayer.addChild(node);
                this.huoYanNodes[1] = node;
            }
            this.huoYanNodes[1].setPosition(data[1]);
            this.huoYanNodes[1].setScale(s);
        } else {
            if (!!this.huoYanNodes[1]) {
                GlobalPool.put(this.huoYanNodes[1]);
                this.huoYanNodes[1] = null;
            }
        }
        if (this.car.isPartFull()) {
            this.showHuoYan();
        } else {
            this.hideHuoYan();
        }
    }
    //#endregion

    /************************************************************运行状态************************************************************/
    protected stepMoving(dt: number) {
        this.updatePartAddSpeed(dt);
        this.cachePos.z += this.speed.z * dt;
        this.node.setPosition(this.cachePos);
        this.rotateToTargetRadianZ(dt);
        this.updateCollScope();
        this.updateStreaks(dt);
    }
    protected stepStand(dt: number) {
        this.rotateToTargetRadianZ(dt);
        this.updateCollScope();
        this.updateStreaks(dt);
    }
    protected stepMoveOnBadTerrain(dt: number) {
        this.updatePartAddSpeed(dt);
        this.cachePos.z += this.speed.z * dt;
        this.node.setPosition(this.cachePos);
        this.rotateToTargetRadianZ(dt);
        this.updateCollScope();
        this.updateStreaks(dt);
        //检测是否离开恶劣地形
        this.checkLevelTerrain();
    }
    protected checkLevelTerrain() {
        if (this.maxZ < this.terrain.minZ || this.minRadian > this.terrain.maxRadian || this.maxRadian < this.terrain.minRadian) {
            this.exitTerrain();
            this.enterCustomUpdateState(GlobalEnum.RoleState.move);
            if (this.isPlayer) {
                this.emit(EventType.LevelEvent.playerExitTerrain);
            }
        }
    }

    protected stepMoveToScoreLine(dt: number) {
        this.updatePartAddSpeed(dt);
        this.cachePos.z += this.speed.z * dt;
        this.node.setPosition(this.cachePos);
        this.rotateToTargetRadianZ(dt);
        this.updateStreaks(dt);
    }

    //todo:终点路段，边跑边掉落零件
    protected elapsedOnScoreRoad: number = 0;
    protected stepMoveOnScoreRoad(dt: number) {
        //掉落零件
        this.updatePartAddSpeed(dt);
        this.elapsedOnScoreRoad += dt;
        if (this.elapsedOnScoreRoad > 0.4) {
            this.elapsedOnScoreRoad = 0;
            if (this.curPartCount > 0) {
                // let count = Math.floor(this.car.getTotalPartCount() / this.car.partGroupCount);
                // this.car.dropPartCount(count);
                // this.curPartCount = this.car.getPartCount();
                // this.emit(EventType.LevelEvent.updatePlayerCurPartCount, this.curPartCount);
                // this.updateSpeed();
            }
        }
        this.cachePos.z += this.speed.z * dt;
        this.node.setPosition(this.cachePos);
        this.updateCollScope();
        this.updateStreaks(dt);
    }

    //终点路段减速前进（AI到达终点或玩家失败到达终点时的状态）    
    protected stepEndRoad(dt: number) {
        this.speed.z *= 0.99;
        if (this.speed.z > -0.1) {
            this.speed.z = 0;
            this.enterCustomUpdateState(GlobalEnum.RoleState.stand);
        }
        this.cachePos.z += this.speed.z * dt;
        this.node.setPosition(this.cachePos);
        this.updateStreaks(dt);
    }


    /************************************************************事件回调************************************************************/
    /**移除障碍物组，更新碰撞范围索引 */
    protected onRemoveBarrierGroupIndex(index: number) {
        if (this.collPtr[GlobalEnum.CollerType.barrierGroup].min > index) {
            this.collPtr[GlobalEnum.CollerType.barrierGroup].min -= 1;
        }
    }

}
